import 'dart:async';
import 'dart:io';

import 'package:base/navigator/route_delegate_decoration.dart';
import 'package:base/navigator/route_parser.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:pipeline/model/db/pipeline_database.dart';
import 'package:pipeline/view/pages/login_page.dart';
import 'package:provider/provider.dart';
import 'view/pages/home_page.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (Platform.isAndroid) {
    //允许调试加载到此应用程序的任何WebView中的Web内容（HTML / CSS / JavaScript）。
    //可以启用此标志，以便于调试在WebViews中运行的Web布局和JavaScript代码。
    await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);

    var swAvailable = await AndroidWebViewFeature.isFeatureSupported(
        AndroidWebViewFeature.SERVICE_WORKER_BASIC_USAGE);
    var swInterceptAvailable = await AndroidWebViewFeature.isFeatureSupported(
        AndroidWebViewFeature.SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST);
    //serviceWorker 离线缓存 应用先访问本地缓存资源，在离线状态时，在没有通过网络接收到更多的数据前，仍可以提供基本的功能（一般称之为 Offline First）。
    if (swAvailable && swInterceptAvailable) {
      AndroidServiceWorkerController serviceWorkerController =
          AndroidServiceWorkerController.instance();
      serviceWorkerController.serviceWorkerClient = AndroidServiceWorkerClient(
        shouldInterceptRequest: (request) async {
          return null;
        },
      );
    }
  }
  //打开数据库 ///退出时关闭
  await PipelineDatabase().open();

  // SystemChrome.setPreferredOrientations(
  //     [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]).then((_) {

  // });
  runApp(
    PipelineApp(),
  );
}

class PipelineApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<PipelineApp> {
  final _appRouteDelegate =
      RouteDelegateDecoration(initialPage: LoginPage()); //设置开始界面

  final _appRouteParser = RouteParser();

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: LoginViewModel()),
        ChangeNotifierProvider.value(value: HomeViewModel()),
      ],
      child: AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarBrightness: Brightness.dark,
          statusBarIconBrightness: Brightness.dark,
        ),
        child: MaterialApp.router(
          title: 'wispipeline',
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          routeInformationParser: _appRouteParser,
          routerDelegate: _appRouteDelegate,
        ),
      ),
    );
  }
}
